<?php
namespace CongoOpenSDK;

/**
 * aes 加密 解密类库
 */
class AES {
    private static $method = 'AES-128-CBC';

    public static function getRandomKey($length = 16) {
        $string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
        $code = '';
         $strlen = strlen($string) - 1;
         for ($i = 0; $i < $length; $i++) {
             $code .= $string[mt_rand(0, $strlen)];
         }
         return $code;
    }

    public static function encrypt($data, $key, $iv)
    {
        $result = openssl_encrypt($data, self::$method, $key, OPENSSL_RAW_DATA, $iv);
        return strtoupper(bin2hex($result));
    }

    public static function decrypt($data, $key, $iv)
    {
        return openssl_decrypt(hex2bin($data), self::$method, $key, OPENSSL_RAW_DATA, $iv);
    }
}

class RSA {
    /**
     * 使用私钥进行加密，对应的使用公钥进行解密
     */
    public static function privateKeyEncrypt($data, $privateKey) {
        if (!openssl_get_privatekey($privateKey)) {
            // 格式化私钥
            $privateKey = chunk_split($privateKey, 64, "\n");
            $privateKey = "-----BEGIN PRIVATE KEY-----\n" . $privateKey . "-----END PRIVATE KEY-----\n";
        }
        $pkeyid = openssl_get_privatekey($privateKey);
        if (!$pkeyid) {
            throw new \Exception('私钥格式不正确');
        }
        $return_en = openssl_private_encrypt($data, $crypted, $pkeyid);
        if(!$return_en){
            throw new \Exception('加密失败,请检查RSA秘钥');
        }
        return strtoupper(bin2hex($crypted)) . '-';
    }

    /**
     * 使用公钥进行解密
     */
    public static function publicKeyDecrypt($data, $publicKey) {
        $data = rtrim($data, '-');
        if (!openssl_get_publickey($publicKey)) {
            // 格式化公钥
            $publicKey = chunk_split($publicKey, 64, "\n");
            $publicKey = "-----BEGIN PUBLIC KEY-----\n" . $publicKey . "-----END PUBLIC KEY-----\n";
        }
        $pkeyid = openssl_get_publickey($publicKey);
        if (!$pkeyid) {
            throw new \Exception('公钥格式不正确');
        }
        $return_de = openssl_public_decrypt(hex2bin($data), $decrypted, $pkeyid);
        if(!$return_de){
            throw new \Exception('解密失败,请检查RSA秘钥');
        }
        return $decrypted;
    }
}
?>
